/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package form.administrador;

import br.entidade.GrupoUsuarios;
import br.entidade.Usuarios;
import br.entidade.business.Business;
import form.JFPrincipal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import superior.mensagens.ErroMensagens;

/**
 *
 * @author Adriano
 */
public class JIUsuario extends javax.swing.JInternalFrame {

    /**
     * Creates new form JIUser
     */
    public JIUsuario() {
        initComponents();
        iniciarComponentes();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel1 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        usuaIdIdusuaLabel = new javax.swing.JLabel();
        usuaNmNmusuaLabel = new javax.swing.JLabel();
        fkPerfilLabel = new javax.swing.JLabel();
        usuaIdIdusuaField = new javax.swing.JTextField();
        nomeField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        fkPerfilCombo = new javax.swing.JComboBox();
        jButton2 = new javax.swing.JButton();
        loginFild = new javax.swing.JTextField();
        usuaNmNmusuaLabel1 = new javax.swing.JLabel();

        setForeground(new java.awt.Color(0, 0, 255));
        setTitle("Usuario");

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        masterTable.setModel(dtm);
        masterTable.setSelectionMode(ListSelectionM­odel.MULTIPLE_INTERVAL_SELECTION);
        lsm = masterTable.getSelectionModel();
        lsm.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    jTTabelaLinhaSelecionada(masterTable);
                }
            }
        });
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(40);

        usuaIdIdusuaLabel.setText("ID:");

        usuaNmNmusuaLabel.setText("Nome:");

        fkPerfilLabel.setText("Perfil:");

        usuaIdIdusuaField.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), usuaIdIdusuaField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), nomeField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        nomeField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                nomeFieldKeyReleased(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/save.png"))); // NOI18N
        saveButton.setToolTipText("Salvar");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/refresh.png"))); // NOI18N
        refreshButton.setToolTipText("Atualizar");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/new.png"))); // NOI18N
        newButton.setToolTipText("Novo");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/Delete.png"))); // NOI18N
        deleteButton.setToolTipText("Deletar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), deleteButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/exit.png"))); // NOI18N
        jButton1.setToolTipText("Sair");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        fkPerfilCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), fkPerfilCombo, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        fkPerfilCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fkPerfilComboActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/botoes/reset.png"))); // NOI18N
        jButton2.setToolTipText("Restaura");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), jButton2, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), loginFild, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        loginFild.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                loginFildKeyReleased(evt);
            }
        });

        usuaNmNmusuaLabel1.setText("Login:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton))
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 662, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usuaIdIdusuaLabel)
                            .addComponent(usuaNmNmusuaLabel)
                            .addComponent(fkPerfilLabel)
                            .addComponent(usuaNmNmusuaLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(loginFild)
                            .addComponent(usuaIdIdusuaField)
                            .addComponent(nomeField)
                            .addComponent(fkPerfilCombo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usuaIdIdusuaLabel)
                    .addComponent(usuaIdIdusuaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usuaNmNmusuaLabel)
                    .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usuaNmNmusuaLabel1)
                    .addComponent(loginFild, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fkPerfilLabel)
                    .addComponent(fkPerfilCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(saveButton)
                        .addComponent(refreshButton)
                        .addComponent(deleteButton)
                        .addComponent(newButton)
                        .addComponent(jButton1))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        
        try {
            dao.salvar();
        } catch (RollbackException e) {
            dao.getEntityManager().getTransaction().begin();
            dao.refresh();
            list = dao.findAll(Usuarios.class);
            ErroMensagens.getInstancia().ErroMensagem("Você deve estar cometendo um dos seguntes erros. \n"
                                                    + "1 - Usuario com Nome vazio. \n"
                                                    + "2 - Usuario com Perfil vazio. \n"
                                                    + "3 - Usuario já cadastrado. ");
            System.err.println("Column 'usua_nm_nmusua' cannot be null " );
        }
        mostraPesquisa();
    }//GEN-LAST:event_saveButtonActionPerformed
    
    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        
        dao.refresh();
        list = dao.findAll(Usuarios.class);
        mostraPesquisa();
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        Usuarios s = new Usuarios();
        s.setSenha("");
        dao.criar(s);
        list.add(s);
        mostraPesquisa();
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_newButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<Usuarios> toRemove = new ArrayList<>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            Usuarios s = list.get(masterTable.convertRowIndexToModel(selected[idx]));
            toRemove.add(s);
            dao.remover(s);
        }
        list.removeAll(toRemove);
        mostraPesquisa();
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        JFPrincipal.setUs(null);
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void nomeFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nomeFieldKeyReleased
        // TODO add your handling code here:
        nomeField.setText(nomeField.getText().toUpperCase());
        list.get(masterTable.getSelectedRow()).setNome(nomeField.getText());
        masterTable.setValueAt(nomeField.getText(), masterTable.getSelectedRow(), 1);        
    }//GEN-LAST:event_nomeFieldKeyReleased

    private void fkPerfilComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fkPerfilComboActionPerformed
        // TODO add your handling code here:
        if (masterTable.getSelectedRow() != -1) {
            if (fkPerfilCombo.getSelectedItem() != null) {
                list.get(masterTable.getSelectedRow()).setGrupoUsuariosId(box.get(fkPerfilCombo.getSelectedIndex() - 1));
            }
            masterTable.setValueAt(fkPerfilCombo.getSelectedItem(), masterTable.getSelectedRow(), 3);
        }
    }//GEN-LAST:event_fkPerfilComboActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        ativarUser(list.get(masterTable.getSelectedRow()));
    }//GEN-LAST:event_jButton2ActionPerformed

    private void loginFildKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_loginFildKeyReleased
        // TODO add your handling code here:
        loginFild.setText(loginFild.getText().toUpperCase());
        list.get(masterTable.getSelectedRow()).setLogin(loginFild.getText());
        masterTable.setValueAt(loginFild.getText(), masterTable.getSelectedRow(), 2);  
    }//GEN-LAST:event_loginFildKeyReleased


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton;
    private javax.swing.JComboBox fkPerfilCombo;
    private javax.swing.JLabel fkPerfilLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField loginFild;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.swing.JTextField nomeField;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField usuaIdIdusuaField;
    private javax.swing.JLabel usuaIdIdusuaLabel;
    private javax.swing.JLabel usuaNmNmusuaLabel;
    private javax.swing.JLabel usuaNmNmusuaLabel1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private List<Usuarios> list;
    private List<GrupoUsuarios> box;
    private DefaultTableModel dtm = new DefaultTableModel(null, new String[]{"Id", "Nome", "Login", "Perfil", "Status"});
    private ListSelectionModel lsm;
    private Business dao;
    
    private void iniciarComponentes() {
        dao = new Business();
        dao.getEntityManager().getTransaction().begin();
        listarPesquisa();
        listarBox();
    }

    private void listarPesquisa() {
        list = dao.findAll(Usuarios.class);
        mostraPesquisa();
    }

    private void mostraPesquisa() {
        while (dtm.getRowCount() > 0) {
            dtm.removeRow(0);
        }
        if (list.isEmpty()) {
            ErroMensagens.getInstancia().AtencaoMensagem("Nenhum resultado encontrado");
        } else {
            String[] linha = new String[]{null, null, null, null, null};
            int i = 0;
            for (Usuarios sftUsua : list) {
                dtm.addRow(linha);
                dtm.setValueAt(sftUsua.getId(), i, 0);
                dtm.setValueAt(sftUsua.getNome(), i, 1);
                dtm.setValueAt(sftUsua.getLogin(), i, 2);
                dtm.setValueAt((sftUsua.getGrupoUsuariosId() != null ? sftUsua.getGrupoUsuariosId().getDescricao(): null), i, 3);
                dtm.setValueAt(sftUsua.isStatus(), i, 4);
                i++;
            }
        }
    }

    public void jTTabelaLinhaSelecionada(JTable masterTable) {
        try{
            usuaIdIdusuaField.setText(String.valueOf(list.get(masterTable.getSelectedRow()).getId()));
            nomeField.setText(list.get(masterTable.getSelectedRow()).getNome());
            loginFild.setText(list.get(masterTable.getSelectedRow()).getLogin());
            fkPerfilCombo.setSelectedItem(null);
            if(list.get(masterTable.getSelectedRow()).getGrupoUsuariosId()!= null)
                fkPerfilCombo.setSelectedItem(list.get(masterTable.getSelectedRow()).getGrupoUsuariosId().getDescricao());
        } catch(ArrayIndexOutOfBoundsException e){
            usuaIdIdusuaField.setText("");
            nomeField.setText("");
            loginFild.setText("");            
            fkPerfilCombo.setSelectedItem(null);
        }
    }

    @SuppressWarnings("unchecked")
    private void listarBox() {
        box = dao.findAll(GrupoUsuarios.class);
        fkPerfilCombo.removeAllItems();
        fkPerfilCombo.addItem(null);
        box.stream().filter((sftPerfil) -> (!sftPerfil.getDescricao().contains("ZZ "))).forEach((sftPerfil) -> {
            fkPerfilCombo.addItem(sftPerfil.getDescricao());
        });
    }

    private void ativarUser(Usuarios s) {
        s.setStatus(true);
        s.setSenha("");
        dao.editar(s);
        mostraPesquisa();
    }
}
